﻿/* *********************************************
 * Crypto libary : DES module
 * Christiaan Rakowski 20110825
 * This module will encrypt the input using the (3)DES algorithm
 * ********************************************/

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace CryptoCs
{
	namespace Encryption
	{
		public class DES
		{
			public static string MasterKey = "A$b*ls5#";

			public static string Encrypt(string originalString)
			{
				return Encrypt(originalString, MasterKey);
			}
			public static string Encrypt(string originalString, string key)
			{
				if (String.IsNullOrEmpty(originalString))
				{
					throw new ArgumentNullException("originalString", "The string which needs to be encrypted can not be null.");
				}
				if(key.Length != 8)
				{
					throw new ArgumentOutOfRangeException("key", key, "A DES encryption key must be exactly 8 characters long");
				}

				DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
				MemoryStream memoryStream = new MemoryStream();
				Byte[] bytes = Encoding.UTF8.GetBytes(key);
				CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateEncryptor(bytes, bytes), CryptoStreamMode.Write);

				StreamWriter writer = new StreamWriter(cryptoStream);
				writer.Write(originalString);
				writer.Flush();
				cryptoStream.FlushFinalBlock();
				writer.Flush();

				return Encoding.UTF8.GetString(memoryStream.GetBuffer());
			}

			public static string Decrypt(string cryptedString)
			{
				return Decrypt(cryptedString, MasterKey);
			}
			public static string Decrypt(string cryptedString, string key)
			{
				if (String.IsNullOrEmpty(cryptedString))
				{
					throw new ArgumentNullException("cryptedString", "The string which needs to be decrypted can not be null.");
				}
				if (key.Length != 8)
				{
					throw new ArgumentOutOfRangeException("key", key, "A DES encryption key must be exactly 8 characters long");
				}

				DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
				MemoryStream memoryStream = new MemoryStream(Convert.FromBase64String(cryptedString));

				Byte[] bytes = Encoding.UTF8.GetBytes(key);
				CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateDecryptor(bytes, bytes), CryptoStreamMode.Read);
				StreamReader reader = new StreamReader(cryptoStream);

				return reader.ReadToEnd();
			}
		}
	}
}
